<template>
  <div class="role">
    <Row class-name="margin-gap">
      <Button type="success" @click="add(true)">新增组</Button>
      <ButtonGroup>
        <template v-for="(role,index) in roleGroup">
          <Button
            :key="index"
            :type="role.ROLE_ID == currentRoleGroup ? 'warning': 'default'"
            v-text="role.ROLE_NAME"
            @click="getData(role.ROLE_ID)"
          ></Button>
        </template>
      </ButtonGroup>
    </Row>

    <Row class-name="margin-gap">本组:
      <Button type="primary" @click="changeName(true)">修改组名称</Button>
      <Button @click="manageMenuqx(true)" v-if="currentRoleGroup == 1">Admin菜单权限</Button>
      <Button @click="manageMenuqx(true)" v-else>组菜单权限</Button>
    </Row>

    <Row class-name="margin-gap">
      <Col span="32" class="padding-left-10">
        <Card>
          <div class="edittable-con-1">
            <Table border :columns="columns" :data="columnsData" no-data-text="您无权查看"></Table>
          </div>
        </Card>
      </Col>
    </Row>

    <Row justify="end" class-name="margin-gap">
      <Col :span="3">
        <Button type="success" @click="add(false)">新增角色</Button>
      </Col>
      <Col class="page-right">
        <Page
          :page-size="pageSize"
          :current="currentPage"
          :total="total"
          :page-size-opts="[15,30]"
          show-total
          show-elevator
          show-sizer
          @on-change="changePage"
          @on-page-size-change="changePageSize"
        ></Page>
      </Col>
    </Row>
    <modalDialog
      @save="saveModal"
      @close="closeModal"
      :modal_type="type"
      :placeholder="modal_ph"
      :treeData="treeData"
      :title="modal_title"
    ></modalDialog>
  </div>
</template>

<script>
import canEditTable from './components/canEditTable.vue'
import modalDialog from './components/modalDialog'
import { parseListAllData } from '@/libs/util'
import { Switch } from 'iview'

export default {
  name: 'role',
  components: {
    canEditTable,
    modalDialog
  },
  data () {
    return {
      roleGroup: [], // 角色组列表
      columns: [
        // 列
        {
          title: '序号',
          key: 'order',
          width: 80,
          render: (h, params) => {
            return h('span', params.index + 1)
          }
        },
        {
          title: '角色',
          key: 'ROLE_NAME',
          width: 160
        },
        {
          title: '编码',
          key: 'RNUMBER'
        },
        {
          title: '状态',
          key: 'STATUS',
          width: 80,
          render: (h, params) => {
            return h(Switch, {
              props: {
                value: parseInt(params.row.STATUS) > 0
              },
              on: {
                'on-change': status => {
                  // 改变状态
                  this.$store.dispatch('handleChangeRoleStatus', {
                    ROLE_ID: params.row.ROLE_ID,
                    STATUS: String(Number(status))
                  }).then((res) => {
                    // console.log(res)
                  }).catch((res) => {
                    console.error(res)
                  })
                }
              }
            })
          }
        },
        {
          title: '增',
          key: 'action',
          align: 'center',
          width: 80,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'success',
                  size: 'small',
                  icon: 'ios-construct'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.getb4(params.row.ROLE_ID, 'add_qx')
                  }
                }
              })
            ])
          }
        },
        {
          title: '删',
          key: 'action',
          align: 'center',
          width: 80,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'success',
                  size: 'small',
                  icon: 'ios-construct'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.getb4(params.row.ROLE_ID, 'del_qx')
                  }
                }
              })
            ])
          }
        },
        {
          title: '改',
          key: 'action',
          align: 'center',
          width: 80,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'success',
                  size: 'small',
                  icon: 'ios-construct'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.getb4(params.row.ROLE_ID, 'edit_qx')
                  }
                }
              })
            ])
          }
        },
        {
          title: '查',
          key: 'action',
          align: 'center',
          width: 80,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'success',
                  size: 'small',
                  icon: 'ios-construct'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.getb4(params.row.ROLE_ID, 'cha_qx')
                  }
                }
              })
            ])
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 250,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.manageMenuqx(false, params.row.ROLE_ID)
                    }
                  }
                },
                '菜单权限'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.changeName(
                        false,
                        params.row.ROLE_ID,
                        params.row.ROLE_NAME
                      )
                    }
                  }
                },
                '编辑'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.roleDelete(params.row.ROLE_ID)
                    }
                  }
                },
                '删除'
              )
            ])
          }
        }
      ],
      columnsData: [], // 行数据
      currentRoleGroup: '', // 当前角色组的id
      currentRole: '', // 当前角色的id
      type: 0, // 显示不同的modal框
      modal_ph: '', // 传给modal的默认值
      modal_title: '', // 传给modal的标题
      treeData: [], // 菜单权限弹框内生成的树结构数据
      btnType: '', // 增删改查类型
      isGroup: false, // 是否是组
      currentPage: 1, // 当前页码
      total: 0, // 数据总数
      pageSize: 10, // 每页显示的数据条数
      hasAccess: true // 是否有权限
    }
  },
  computed: {},
  methods: {
    changePage (page) { // 电梯跳转是 keyup.enter，使用时需要注意
      this.getData(this.currentRoleGroup, page, this.pageSize)
    },
    changePageSize (size) { // 改变每页显示的size
      if (size) {
        this.pageSize = size
        this.getData(this.currentRoleGroup, this.currentPage, size)
      }
    },
    add (isGroup) { // 添加组、角色
      this.type = 1
      this.modal_title = '新增'
      this.isGroup = isGroup || false
    },
    changeName (isGroup, id, name) { // 修改组名、角色名
      if (!name) name = this.getGroupData(this.currentRoleGroup, 'ROLE_NAME') // 组名
      this.type = 2
      this.currentRole = id || ''
      this.modal_ph = name
      this.isGroup = isGroup || false
      this.modal_title = '编辑'
    },
    roleDelete (id) { // 删除角色
      this.$store.dispatch('handleDeleteRole', {
        ROLE_ID: id
      }).then(res => {
        // 更新数据
        const role = this.currentRoleGroup
        const page = this.currentPage
        const size = this.pageSize
        this.getData(role, page, size)
      }).catch((err) => {
        console.error(err) // 处理出错
      })
    },
    manageMenuqx (isGroup, id) { // 获取菜单权限数据
      const $this = this
      if (id === undefined) id = this.currentRoleGroup

      this.isGroup = false
      this.currentRole = id
      this.modal_title = '菜单权限'
      this.type = 3

      this.$store.dispatch('handleGetMenuqx', { ROLE_ID: id }).then(res => {
        $this.setTreeData(res) // 把获取到的数据赋给tree组件
      }).catch((err) => {
        console.error(err) // 处理出错
      })
    },
    getb4 (id, type) {
      // 获取增删改查数据
      const $this = this
      let title

      switch (type) {
        case 'add_qx':
          title = '授权新增权限(此角色下打勾的菜单拥有新增权限)'
          break
        case 'del_qx':
          title = '授权删除权限(此角色下打勾的菜单拥有删除权限)'
          break
        case 'edit_qx':
          title = '授权修改权限(此角色下打勾的菜单拥有修改权限)'
          break
        case 'cha_qx':
          title = '授权查看权限(此角色下打勾的菜单拥有查看权限)'
          break
        default:
          title = '菜单权限'
          break
      }

      this.type = 4
      this.modal_title = title
      this.currentRole = id
      this.btnType = type

      this.$store.dispatch('handleGetb4Button', {
        ROLE_ID: id,
        MSG: type
      }).then(res => {
        $this.setTreeData(res)
      }).catch((err) => {
        console.error(err)
      })
    },
    saveModal (value) { // 保存弹框返回的数据
      const par = this.isGroup ? 0 : this.currentRoleGroup
      const id = this.currentRole || this.currentRoleGroup
      const $this = this

      switch (this.type) {
        case 1:
          this.$store.dispatch('handleAddRole', {
            ROLE_NAME: value,
            PARENT_ID: par // 组： 0，角色： 父节点ROLE_ID
          }).then((res) => {
            // 更新
            if (!res.data) res.data = {}
            const newRole = res.data.result.pd
            if (this.isGroup) {
              this.getData(newRole.ROLE_ID)
            } else {
              this.getData(id)
            }
            this.closeModal() // isGroup还会有作用
          }).catch((err) => {
            console.error(err)
          })
          break
        case 2:
          this.$store.dispatch('handleEditRole', {
            ROLE_ID: id,
            ROLE_NAME: value
          }).then((res) => {
            this.updateName(id, value) // 更新名称
            this.closeModal()
          }).catch((err) => {
            console.error(err)
          })
          break
        case 3:
          $this.$store.dispatch('handleSaveMenuqx', {
            ROLE_ID: id,
            MENUIDS: value // 被选中的菜单id ［string］
          }).then(() => {
            $this.closeModal()
          }).catch((err) => {
            console.error(err)
          })
          break
        case 4:
          $this.$store.dispatch('handleSaveb4Button', {
            ROLE_ID: id,
            MENUIDS: value,
            MSG: $this.btnType
          }).then(() => {
            $this.closeModal()
          }).catch((err) => {
            console.err(err)
          })
          break
      }
    },
    closeModal () {
      // 关闭modal 恢复默认属性
      this.type = 0
      this.currentRole = ''
      this.modal_ph = ''
      this.isGroup = false
      this.modal_title = ''
      this.treeData = []
      this.btnType = ''
    },
    setTreeData (res) { // 设置 tree 数据
      if (!res) return
      if (!res.data) res.data = {}
      const nodeData = JSON.parse(res.data.result.zTreeNodes)
      this.treeData = parseListAllData(nodeData)
    },
    updateName (id, name) { // 更新名字
      let data = this.isGroup ? this.roleGroup : this.columnsData // 组或者角色
      for (let i = 0; i < data.length; i++) {
        if (parseInt(data[i].ROLE_ID) === parseInt(id)) { data[i].ROLE_NAME = name }
      }
    },
    getData: function (id, page, size) { // 根据id 获取role数据，默认取admin的数据 ,page: 页码 , size: 每页显示条数
      const $this = this
      if (this.hasAccess) {
        this.$store.dispatch('handleGetRoleList', { id, page, size }).then(res => {
          $this.updateData(res, id)
        }).catch((res) => {
          console.error(res, this)
        })
      }
    },
    updateData (res, id) { // 更新组件内的数据，包括组array、当前组id、当前组下的角色数据等
      if (!res) res = {}
      if (!res.data) res.data = {}
      if (!res.data.result) res.data.result = {}
      const result = res.data.result
      const hasAccess = result.QX.chas
      if (parseInt(hasAccess) === 1) {
        this.roleGroup = result.roleList
        this.columnsData = result.roleList_z
        this.currentRoleGroup = id === undefined ? this.roleGroup[0].ROLE_ID : id
        this.currentPage = Number(result.Page.currentPage) || 1
        this.total = Number(result.Page.totalResult) || 0
        this.pageSize = Number(result.Page.showCount) || 10
        this.hasAccess = true
      } else this.hasAccess = false
    },
    getGroupData (id, prop) { // 根据id找到对应的组 ，并获取prop属性值
      const group = this.roleGroup
      let result = ''
      for (let i = 0; i < group.length; i++) {
        if (parseInt(group[i].ROLE_ID) === parseInt(id)) {
          result = group[i][prop]
          break
        }
      }
      return result
    }
  },
  created () {
    this.getData()
  }
}
</script>
<style lang="less">
.page-right {
  float: right;
  &:after {
    clear: both;
  }
}
.margin-gap {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
